﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace YTSK.FrmList
{
    public partial class FrmRD11List : Form
    {

        #region 初始化
        public FrmRD11List()
        {
            try
            {
                InitializeComponent();
                this.Icon = YTSK.Properties.Resources.Fly;
                this.Text = string.Format("销售出库单列表---版本{0}-{1}-{2}",
                    ServerConfig.Version.ToString("yyyyMMdd"), ServerConfig._company, ServerConfig.UserName);

                Common.HandleReport.InitControl(this, this.dataGridView1, "v_rdreocrd11_wkp");
                this.Resize += frmMain_Resize;
                this.dataGridView1.CellMouseDoubleClick += dataGridView1_MouseDoubleClick;
                foreach (ToolStripItem bar in this.toolStrip1.Items)
                {
                    if (bar.Text.Length > 0)
                    { bar.Click += toolbar_click; }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion 

        #region 双击选中行
        public void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                var row = this.dataGridView1.CurrentRow;
                if (row == null) { return; }
                var obj = row.Cells["ID"].Value.ObjToInt();
                //var cDefine2 = row.Cells["cDefine2"].Value.ObjToString();
                if (obj != 0)
                {
                    //if (ServerConfig._company ==  Company.广州易腾 )
                    //{
                    //    var f = new FrmVouch();
                    //    f.Show();
                    //    f.voudefine.Reflesh(obj);
                    //}
                    //else
                    //{
                    var f1 = new FrmKP.FrmLSD();
                    f1.Show();
                    f1.voudefine.Reflesh_Rd(obj);
                    GetReportData();
                    //}

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 全选
        private bool _bSel = true;
        private void SelectAll(object sender, EventArgs e)
        {
            var dg = this.dataGridView1;
            for (int i = 0; i < dg.Rows.Count; i++)
            {
                var row = dg.Rows[i];
                row.Cells["selcol"].Value = _bSel ? "√" : (row.Index + 1).ToString();
            }
            _bSel = !_bSel;
        }

        #endregion

        #region 窗体大小
        private void frmMain_Resize(object sender, EventArgs e)
        {
            if (this.Width > 40)
            { this.dataGridView1.Width = this.Width - 40; }
            if (this.Height > 200)
            {
                this.dataGridView1.Height = this.Height - 200;
            }
        }
        #endregion

        #region 报表数据
        private void btQuery_Click(object sender, EventArgs e)
        {
            GetReportData();
        }
        /// <summary>
        /// 获取报表数据
        /// </summary>
        private void GetReportData()
        {
            Common.HandleReport.GetGridData(this.groupBox2, this.dataGridView1, "v_rdreocrd11_wkp");
        }
        #endregion

        #region 工具栏事件
        public virtual void toolbar_click(object sender, EventArgs e)
        {
            if (sender.GetType() != typeof(ToolStripButton)) { return; }
            var bt = (ToolStripButton)sender;
            var text = bt.Text;
            switch (text)
            {
                case "导出":
                    Common.handleDataGrid.ExportExcel(this.dataGridView1);
                    break;
                case "审核":
                    Verify();
                    //DownLoadFromERP(para0);
                    break;
                case "弃审":
                    UnVerify();
                    break;
                case "删除":
                    Delete();
                    break;
                case "手工回写":
                    WriteFPHM();
                    break;
                case "拆单开票":
                    OMSKP();
                    break;
                case "退出":
                    this.Close();
                    break;
                case "批量开电票":
                    BatchDZFP();
                    break;
                case "批量云状态":
                    BatchFPStatus();
                    break;
                default:
                    MessageBox.Show("没有找到程序");
                    break;
            }

        }
        #endregion

        #region 工具栏的所有方法
        #region 批量电子发票
        /// <summary>
        /// 批量电子发票
        /// </summary>
        public void BatchDZFP()
        {
            var err = "";
            int idold = 0;
            var dg = this.dataGridView1;
            for (int i = 0; i < dg.Rows.Count; i++)
            {
                var row = dg.Rows[i];
                var fplx = row.Cells["cBillType"].Value.ObjToString();
                if (!fplx.Contains("电子"))
                {
                    err = string.Format("第[{0}]行为[{1}]", i + 1, fplx);
                    MessageBox.Show(err);
                    return;
                }
            }
            err = string.Format("总共有[{0}]行数据，确认继续", dg.Rows.Count);
            var dr = MessageBox.Show(err, "提示", MessageBoxButtons.YesNo);
            if (dr == DialogResult.No) { return; }
            var ftip = new FrmTip();

            ftip.Show(this);
            ftip.setValue("开始生成电子发票");
            this.Enabled = false;
            try
            {
                int isuccount = 0;
                for (int i = 0; i < dg.Rows.Count; i++)
                {
                    var row = dg.Rows[i];
                    var id = row.Cells["ID"].Value.ObjToInt();
                    if (id == idold) { continue; }

                    var url = string.Format("{0}/api/oms/Rd2SK/GetOneForKP?token={1}&id={2}",
                    ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
                    var s = Common.handleHttp.Get(url);
                    var result = Common.handleJSON.DeserializeResult(s);
                    if (result.result != 1) { ftip.Hide(); MessageBox.Show(result.resultdetail); return; }
                    var t = (Dictionary<string, object>)result.GetVal("main");
                    var rd = t.ToObj<Model.Rdrecord_View>();

                    if (rd.cBillType.Contains("电子"))
                    {
                        var tipmsg = string.Format("正在发送开票[{0}][{1}/{2}]", rd.cCode, i + 1, dg.Rows.Count);
                        var bret =Vouch.VouchToolBar.VouchToFP_RD_Proc(rd.ID);
                        if (!bret)
                        {
                            return;
                        }
                        isuccount++;
                        idold = id;
                        ftip.setValue(string.Format("单据[{0}]发送电子发票请求成功[{1}/{2}]",
                            rd.cCode, i + 1, dg.Rows.Count));
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                err = string.Format("成功发送了[{0}]个开票申请", isuccount);
                ftip.Hide();
                MessageBox.Show(err);
            }
            finally { this.Enabled = true; ftip.Close(); }
        }
        #endregion 

        #region 审核按钮
        public void Verify()
        {
            try
            {
                var dg = this.dataGridView1;
                var url = string.Format("{0}/api/oms/Rdrecord11/VerifyTry?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                var currentrow = dg.CurrentRow;
                var _id = currentrow.Cells["ID"].Value.ObjToInt();
                var _ts = currentrow.Cells["ts"].Value.ObjToString();
                var pos = new Dictionary<string, object>();
                pos.Add("ID", _id);
                pos.Add("ts", _ts);
                var s = Common.handleHttp.Post(pos, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == -1 || result.result == 1002)
                {
                    MessageBox.Show(result.resultdetail); return;
                }
                if (result.result == 1001)
                {
                    var dr = MessageBox.Show(result.resultdetail, "提示", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No)
                    { return; }
                }

                url = string.Format("{0}/api/oms/Rdrecord11/Verify?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                s = Common.handleHttp.Post(pos, url);
                result = Common.handleJSON.DeserializeResult(s);

                if (result.result != 1) { MessageBox.Show("审核出错:" + result.resultdetail); return; }
                MessageBox.Show("审核成功!");
                GetReportData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 弃审核
        public void UnVerify()
        {
            try
            {
                var dg = this.dataGridView1;
                var url = string.Format("{0}/api/oms/Rdrecord11/UnVerifyTry?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                var currentrow = dg.CurrentRow;
                var _id = currentrow.Cells["ID"].Value.ObjToInt();
                var _ts = currentrow.Cells["ts"].Value.ObjToString();
                var pos = new Dictionary<string, object>();
                pos.Add("ID", _id);
                pos.Add("ts", _ts);
                var s = Common.handleHttp.Post(pos, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == -1 || result.result == 1002)
                {
                    MessageBox.Show(result.resultdetail); return;
                }
                if (result.result == 1001)
                {
                    var dr = MessageBox.Show(result.resultdetail, "提示", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No)
                    { return; }
                }

                url = string.Format("{0}/api/oms/Rdrecord11/UnVerify?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                s = Common.handleHttp.Post(pos, url);
                result = Common.handleJSON.DeserializeResult(s);

                if (result.result != 1) { MessageBox.Show("弃审出错:" + result.resultdetail); return; }
                MessageBox.Show("弃审成功!");
                GetReportData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 删除按钮
        public void Delete()
        {
            try
            {
                var dg = this.dataGridView1;
                var url = string.Format("{0}/api/oms/Rdrecord11/Delete?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                var currentrow = dg.CurrentRow;
                var _id = currentrow.Cells["ID"].Value.ObjToInt();
                var _ts = currentrow.Cells["ts"].Value.ObjToString();
                var pos = new Dictionary<string, object>();
                pos.Add("ID", _id);
                pos.Add("ts", _ts);
                var s = Common.handleHttp.Post(pos, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == -1 || result.result == 1002)
                {
                    MessageBox.Show(result.resultdetail); return;
                }
                if (result.result == 1001)
                {
                    var dr = MessageBox.Show(result.resultdetail, "提示", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No)
                    { return; }
                }
                MessageBox.Show("删除成功!");
                #region 显示数据
                GetReportData();
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 拆单开票
        /// <summary>
        /// 拆单开票
        /// </summary>
        public void OMSKP()
        {
            var dg = this.dataGridView1;
            try
            {
                var currentrow = dg.CurrentRow;
                if (currentrow == null) { MessageBox.Show("还没有选择数据"); return; }
                var _id = currentrow.Cells["ID"].Value.ObjToInt();
                Vouch.VouchToolBar.CDKP(_id);
                GetReportData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 手工回写发票
        public void WriteFPHM()
        {
            var dg = this.dataGridView1;
            try
            {
                var currentrow = dg.CurrentRow;
                if (currentrow == null) { MessageBox.Show("还没有选择数据"); return; }
                var id = currentrow.Cells["ID"].Value.ObjToInt();
                string err;
                var fback = new FrmKP.FrmReturn_Rd(id, "", "", WriteBackType.手工回写, DateTime.Now, out err);
                if (err.Length > 0) { MessageBox.Show(err); return; }
                fback.ShowDialog();
                GetReportData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 批量云状态


        #region 批量获取电子发票状态
        /// <summary>
        /// 批量获取电子发票状态
        /// </summary>
        public void BatchFPStatus()
        {
            var ddate = dateStart.Value;
            var url = string.Format("{0}/api/oms/Rd2SK/GetFPStatusSKAll?token={1}&iYear={2}&iMonth={3}",
             ServerConfig.ServerAddress, ServerConfig.GetToken(), ddate.Year, ddate.Month);
            var s = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(s);
            if (result.result == 1) 
            {
                var msg = System.Web.HttpUtility.UrlDecode(result.resultdetail);
                var fmsg = new FrmMessage();
                fmsg.ShowMsg(true, "获取状态", msg);
            }
            else
            {
                var fmsg = new FrmMessage();
                fmsg.ShowMsg(false, "获取状态", result.resultdetail);
            }
        }
        #endregion


        #endregion 

        #endregion

    }
}
